import React, { PureComponent } from 'react';
import { FormattedMessage, formatMessage } from 'umi/locale';
import { LogoutOutlined } from '@ant-design/icons';
import { Spin, Tag, Menu, Avatar, Tooltip } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import groupBy from 'lodash/groupBy';
import router from 'umi/router';
import NoticeIcon from '../NoticeIcon';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';
import robotIcon from '../../assets/robot.gif';

@connect(({ login }) => ({
  login,
}))
class GlobalHeaderRight extends PureComponent {
  getNoticeData() {
    const { notices = [] } = this.props;
    if (notices.length === 0) {
      return {};
    }
    const newNotices = notices.map(notice => {
      const newNotice = { ...notice };
      if (newNotice.datetime) {
        newNotice.datetime = moment(notice.datetime).fromNow();
      }
      if (newNotice.id) {
        newNotice.key = newNotice.id;
      }
      if (newNotice.extra && newNotice.status) {
        const color = {
          todo: '',
          processing: 'blue',
          urgent: 'red',
          doing: 'gold',
        }[newNotice.status];
        newNotice.extra = (
          <Tag color={color} style={{ marginRight: 0 }}>
            {newNotice.extra}
          </Tag>
        );
      }
      return newNotice;
    });
    return groupBy(newNotices, 'type');
  }

  getUnreadData = noticeData => {
    const unreadMsg = {};
    Object.entries(noticeData).forEach(([key, value]) => {
      if (!unreadMsg[key]) {
        unreadMsg[key] = 0;
      }
      if (Array.isArray(value)) {
        unreadMsg[key] = value.filter(item => !item.read).length;
      }
    });
    return unreadMsg;
  };

  changeReadState = clickedItem => {
    const { id, vno } = clickedItem;
    const { dispatch } = this.props;
    dispatch({
      type: 'global/changeNoticeReadState',
      payload: { sysMsgId: id, vno },
    });
  };

  getUrl = clickedItem => {
    const { id } = clickedItem;
    const { dispatch, location } = this.props;
    const { pathname } = location;
    dispatch({
      type: 'global/fetchMsgUrl',
      payload: { sysMsgId: id },
      callback: response => {
        if (response.data) {
          if (response.data.msgUrl === pathname) {
            router.go(0);
          }
          if (response.data.reqParamType === 1) {
            router.push(`${response.data.msgUrl}&isNoticeClick=true`);
          } else {
            // 列表
            const routerParams = {
              pathname: response.data.msgUrl,
              queryParam: JSON.parse(response.data.dataParam),
              query: {
                isNoticeClick: true,
                activeKey: response.data.dataParam.curStep || '1',
              },
            };
            router.push(routerParams);
          }
        }
      },
    });
  };

  fetchMoreNotices = tabProps => {
    const { dispatch, noticeCurrentPage, messageCurrentPage } = this.props;
    const sendType = tabProps.name === 'notification' ? 1 : 2;
    const currentPage = tabProps.name === 'notification' ? noticeCurrentPage : messageCurrentPage;
    const inParam = {
      status: 2,
      sendType,
      currentPage,
      pageSize: 5,
    };
    dispatch({
      type: 'global/fetchMoreNotices',
      payload: inParam,
    });
  };

  // 消息通知的切换
  noticeTabChange = tabTitle => {
    const { dispatch } = this.props;

    dispatch({
      type: 'global/setSendType',
      payload: {
        sendType: tabTitle.indexOf('notification') > -1 ? 1 : 2,
      },
    });
  };

  componentDidMount = () => {};

  /**
   * 系统切换事件
   * @param {*} param0
   */
  handleSystemChange = ({ key }) => {
    const {
      dispatch,
      route: { routes, authority },
    } = this.props;
    dispatch({
      type: 'login/systemChange',
      payload: { sysId: key, routes, authority },
    });
  };

  /**
   * 渲染系统列表
   */
  // getSystemMenuList = () => {
  //   const { systemList } = this.props;
  //   if (systemList.length > 1) {
  //     return (
  //       <Menu onClick={this.handleSystemChange}>
  //         {systemList.map(system => (
  //           <Menu.Item key={system.sysId}>
  //             <a>{system.sysName}</a>
  //           </Menu.Item>
  //         ))}
  //       </Menu>
  //     );
  //   }
  //   return null;
  // };

  // renderSystemMenuList = () => {
  //   const {
  //     login: { currentSystem },
  //   } = this.props;
  //   const SystemMenu = this.getSystemMenuList();
  //   if (SystemMenu) {
  //     return (
  //       <Dropdown overlay={SystemMenu} onClick={e => e.preventDefault()}>
  //         <a className="ant-dropdown-link">
  //           {currentSystem?.sysName} <DownOutlined />
  //         </a>
  //       </Dropdown>
  //     );
  //   }
  //   return null;
  // };

  render() {
    const {
      currentUser,
      fetchingMoreNotices,
      fetchingNotices,
      loadedAllNotices,
      onNoticeVisibleChange,
      onMenuClick,
      onNoticeClear,
      skeletonCount,
      theme,
      notifyTotalCount,
      noticeCount,
      messageCount,
      systemList,
    } = this.props;
    let userSysCode = 'cs';
    systemList.forEach(item => {
      if (item.isSelected) {
        switch (item.sysCode) {
          case 1:
            userSysCode = 'cs';
            break;
          case 2:
            userSysCode = 'ns';
            break;
          case 3:
            userSysCode = 'es';
            break;
          case 4:
            userSysCode = 'os';
            break;
          case 6:
            userSysCode = 'mgr';
            break;
          default:
            userSysCode = 'cs';
            break;
        }
      }
    });
    const menu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
        <Menu.Item key="logout">
          <LogoutOutlined />
          <FormattedMessage id="menu.account.logout" defaultMessage="logout" />
        </Menu.Item>
      </Menu>
    );

    const loadMoreProps = {
      skeletonCount,
      loadedAll: loadedAllNotices,
      loading: fetchingMoreNotices,
    };
    const noticeData = this.getNoticeData();
    let className = styles.right;
    if (theme === 'dark') {
      className = `${styles.right}  ${styles.dark}`;
    }
    return (
      <div className={className}>
        {/* 已改为在SiderMenu组件中切换,注释掉 */}
        {/* {this.renderSystemMenuList()} */}
        {/* <Tooltip title={formatMessage({ id: 'component.globalHeader.help' })}>
          <a
            target="_blank"
            href={`http://fns.fesco.com.cn/docs/${userSysCode}/${userSysCode}-cn`}
            rel="noopener noreferrer"
            className={styles.action}
          >
            <img
              alt="使用文档"
              src={robotIcon}
              style={{ display: 'inline-block', width: 20, height: 20 }}
            />
          </a>
        </Tooltip> */}
        <NoticeIcon
          className={styles.action}
          count={notifyTotalCount}
          onItemClick={(item, tabProps) => {
            this.changeReadState(item, tabProps);
            if (item.type === 'notification') {
              this.getUrl(item, tabProps);
            }
          }}
          locale={{
            emptyText: formatMessage({ id: 'component.noticeIcon.empty' }),
            clear: formatMessage({ id: 'component.noticeIcon.clear' }),
            loadedAll: formatMessage({ id: 'component.noticeIcon.loaded' }),
            loadMore: formatMessage({ id: 'component.noticeIcon.loading-more' }),
          }}
          onClear={onNoticeClear}
          onLoadMore={this.fetchMoreNotices}
          onPopupVisibleChange={onNoticeVisibleChange}
          loading={fetchingNotices}
          onTabChange={this.noticeTabChange}
          clearClose
        >
          <NoticeIcon.Tab
            count={noticeCount}
            list={noticeData.notification}
            title={formatMessage({ id: 'component.globalHeader.notification' })}
            name="notification"
            emptyText={formatMessage({ id: 'component.globalHeader.notification.empty' })}
            emptyImage="https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg"
            scrollToLoad={false}
            {...loadMoreProps}
          />
          <NoticeIcon.Tab
            count={messageCount}
            list={noticeData.message}
            title={formatMessage({ id: 'component.globalHeader.message' })}
            name="message"
            scrollToLoad={false}
            emptyText={formatMessage({ id: 'component.globalHeader.message.empty' })}
            emptyImage="https://gw.alipayobjects.com/zos/rmsportal/sAuJeJzSKbUmHfBQRzmZ.svg"
            {...loadMoreProps}
          />
        </NoticeIcon>
        {currentUser.userName ? (
          <HeaderDropdown overlay={menu}>
            <span className={`${styles.action} ${styles.account}`}>
              <Avatar
                size="small"
                className={styles.avatar}
                src={
                  currentUser.userPortrait
                    ? `/mgrApi/fileServer/showImage?fileId=${currentUser.userPortrait}`
                    : currentUser.avatar
                }
                alt="avatar"
              />
              <span className={styles.name}>{currentUser.userName}</span>
            </span>
          </HeaderDropdown>
        ) : (
          <Spin size="small" style={{ marginLeft: 8, marginRight: 8 }} />
        )}
      </div>
    );
  }
}
export default GlobalHeaderRight;
